package com.mantbox.channelcall.utils;

import com.alibaba.fastjson.JSON;
import com.mantbox.channelcall.entity.Report;
import com.mantbox.channelcall.entity.UrlLink;
import com.mantbox.channelcall.service.ReportService;
import com.mantbox.channelcall.service.UrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@Component
public class UrlUtils {

    @Autowired
    UrlService urlService;
    @Autowired
    ReportService reportService;

    /*根据id生成测试链接*/
    public String generateUrlByUrlId(String urlId,String idfa) {
        String url = "";
        UrlLink link = urlService.selectById(Integer.parseInt(urlId));
        String testIdfa = StringUtils.hasLength(idfa)?idfa:"6C4F0CC4-50D7-430B-A0F3-839C6DDA96FD";
        Report report = reportService.selectByIdfa(testIdfa);
        String call = String.format("http://81.68.211.187/channelcall/call/call?uid=%s&urlId=%d&ts=%d&id=%s&rqId=%s",report.getUid(),link.getId(),System.currentTimeMillis(),report.getId(), UUID.randomUUID());

        url = generateIosFullUrl(link,report,call);
        return url;
    }

    public String ramdomIdfa() {
//        626363D0-90D4-06BF-C281-384E4E69D3E2
        String[] values = new String[]{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int length = values.length;
        Random random = new Random();
        String part1 = "";
        for (int i = 0; i < 8; i ++) {
            int num = random.nextInt(length - 1);
            part1 += values[num];
        }

        String part2 = "";
        for (int i = 0; i < 4; i ++) {
            int num = random.nextInt(length - 1);
            part2 += values[num];
        }

        String part3 = "";
        for (int i = 0; i < 4; i ++) {
            int num = random.nextInt(length - 1);
            part3 += values[num];
        }

        String part4 = "";
        for (int i = 0; i < 4; i ++) {
            int num = random.nextInt(length - 1);
            part4 += values[num];
        }

        String part5 = "";
        for (int i = 0; i < 12; i ++) {
            int num = random.nextInt(length - 1);
            part5 += values[num];
        }
        String sIdfa = part1 + "-" + part2 + "-" + part3 + "-" + part4 + "-" + part5;
        return sIdfa;
    }

    String imei() {
//        868540050954128
        String imei = "";
        Random random = new Random();
        for (int i = 0; i <= 15; i ++ ) {
            imei += random.nextInt(9);
        }
        return imei;
    }



    /**
     * 生成简化的UUID（去掉连字符）
     */
    public static String generateSimpleUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /*根据参数配置生成完整的链接*/
    String generateIosFullUrl(UrlLink link,Report report,String call) {
        String url = "";
        if (!StringUtils.hasLength(link.getParam())) {
            return link.getUrl();
        }
        try {
            List<Map> params = JSON.parseArray(link.getParam(),Map.class);
            Map<String,String> reportObject = JSON.parseObject(JSON.toJSONString(report),Map.class);
            url = link.getUrl();
            /*子链接*/
            String subUrl = "";
            String ts = "";
            for (Map<String,String> obj : params) {
                /*提交字段*/
                String paramKey = obj.get("paramKey");
                /*字段*/
                String key = obj.get("key");
                if (!StringUtils.hasLength(paramKey)) {
                    paramKey = key;
                }
                /*值获取类型*/
                String type = obj.get("type");
                /*编码方式*/
                String encodeType = obj.get("encode");
                /*大小写方式*/
                String caseType = obj.get("case");
                /*md5编码方式*/
                String md5EncodeType = obj.get("md5Encode");
                //要拼接的值
                String value = "";
                /*获取拼接的值*/
                if (StringUtils.hasLength(type)) {
                    if (type.equals(ParamType.DATABASE.name)) {
                        if (key.equals("idfa") && obj.get("mode") != null && obj.get("mode").equals("random")) {
                            value = ramdomIdfa();
                        }else {
                            value = reportObject.get(key);
                        }
                        if (key.equals("imei")) {
                            if (!StringUtils.hasLength(value)) {
                                value = imei();
                            }
                        }
                        if (key.equals("oaid")) {
                            if (!StringUtils.hasLength(value)) {
                                value = UUID.randomUUID().toString();
                            }
                        }
                    }else if (type.equals(ParamType.CALL.name)) {
                        value = call;
                    }else if (type.equals(ParamType.UUID.name)) {
                        String mode = obj.get("mode");
                        if (StringUtils.hasLength(mode) && mode.equals("simple")) {
                            value = generateSimpleUUID();
                        }else {
                            value = UUID.randomUUID().toString();
                        }
                    }else if (type.equals(ParamType.TIME.name)) {
                        String tsType = obj.get("tsType");
                        Long tsLong = System.currentTimeMillis();
                        ts = tsLong + "";
                        if (StringUtils.hasLength(tsType) && tsType.equals("seconds")) {
                            tsLong = tsLong / 1000;
                        }
                        value = tsLong + "";
                    }else if (type.equals(ParamType.PHONE.name)) {
                        if (link.getPlatform() == 0){
                            value = UaOsParser.androidModel(report.getUa());
                        }else  {
                            value = IphoneModelUtils.getPhoneModel();
                        }
                    }
                }
                /*查看使用哪种编码*/
                if (StringUtils.hasLength(encodeType) && StringUtils.hasLength(value) && !type.equals(ParamType.PHONE.name)) {
                    if (encodeType.equals(ParamEncodeType.MD5.name)) {
                        if (md5EncodeType.equals("low")) {
                            value = MD5Utils.MD5Lower(value);
                        }else {
                            value = MD5Utils.MD5Upper(value);
                        }
                    }else if (encodeType.equals(ParamEncodeType.URLENCODED.name)) {
                        try {
                            value = URLEncoder.encode( value, "UTF-8" );
                            value = value.replaceAll("\\+", "%20");
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                if (StringUtils.hasLength(caseType) && StringUtils.hasLength(value)) {
                    if (caseType.equals("up")) {
                        value = value.toUpperCase(Locale.ROOT);
                    }else if (caseType.equals("low")) {
                        value = value.toLowerCase(Locale.ROOT);
                    }
                }
                subUrl += paramKey + "=" + value + "&";
            }
            subUrl = subUrl.substring(0, subUrl.lastIndexOf("&"));
            String firstApped = url.contains("?")?"&":"?";
            url = url + firstApped + subUrl;
            url = url.replaceAll(" ","");
            if (link.getId() == 1327) {
                url = url + "&token=" + url1327GenerateToken(ts);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    String url1327GenerateToken(String ts) {
        String token = "Ro0NjS" + "25288c6570c346f3a80929ba83ab4d2c" + ts;
        token = MD5Utils.MD5Lower(token);
        return token;
    }

}
